package com.xm.clj.underserver.utils;

import com.xm.clj.underserver.bean.LogUser;
import com.xm.clj.underserver.bean.RegUser;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserInfo {

    public static int doLogin(LogUser logUser, JdbcTemplate jdbcTemplate){
        //检查信息是否完整
        if (logUser.getAccount_id()==null || logUser.getPassword()==null){
            return 1;
        }
        //检查账号是否存在
        if (DBUtils.findUser(logUser.getAccount_id())){
            return 2;
        }
        //检查密码是否正确
        if (!DBUtils.findPassword(logUser.getAccount_id(), logUser.getPassword())){
            return 3;
        }
        return 0;
    }

    public static int doRegUser(RegUser user,JdbcTemplate jdbcTemplate){
        //检查信息是否完整
        if (user.getAccount_id()==null||user.getPassword()==null||
                user.getRepassword()==null||user.getUsername()==null){
            return 1;
        }
        //检查格式符号是否违规
        //账号只能由数字、字母组合
        if (isValid(user.getAccount_id())){
            return 2;
        }
        //检查账号是否已经存在
        if (!DBUtils.findUser(user.getAccount_id())){
            return 3;
        }
        //检查两次密码是否相同
        if (!user.getPassword().equals(user.getRepassword())){
            return 4;
        }
        //记录到数据库
        DBUtils.writeIntoUser(user);
        return 0;
    }

    private static boolean isValid(String str) {
        char[] chars = str.toCharArray();
        for (char ch : chars ){
            if ((ch>='0'&&ch<='9')||(ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){
                return false;
            }
        }
        return true;
    }
}
